<template>
	<div class="chartBox">
		<template v-if="userInfo.teamId">
			<div class="chart_title">
				<mu-select-field @change="getCharts($event)" :maxHeight="300" v-model="nameVal" :autoWidth="true" style="width: 120px;">
				    <mu-menu-item v-for="(item, index) in select_name" :key="index" :title="item.userName" :value="index"/>
				</mu-select-field>
				<mu-select-field @change="getCharts($event)" :maxHeight="300" v-model="cycleVal" :autoWidth="true" style="width: 120px;">
				    <mu-menu-item v-for="(item, index) in select_cycle" :key="index" :title="item" :value="index"/>
				</mu-select-field>
			</div>

			<div id="chart1" class="chart_frame"></div>
			<div id="chart2" class="chart_frame"></div>
			<div id="chart3" class="chart_frame"></div>
			<div id="chart4" class="chart_frame"></div>
		</template>
		<template v-else>
			<div class="noData">您必须先加入一个团队才可以使用本功能！</div>
		</template>
	</div>
</template>

<script>
import echarts from 'echarts';
import axios from 'axios';
import { mapState } from 'vuex';
export default{
	data(){
		return {
			select_name: [],
	        nameVal: 0,
			select_cycle: ['周报', '月报'],
	        cycleVal: 0
		}
	},
	computed: mapState(['userInfo']),
	methods: {
		//月图表
		chart_month(str, dates, complete){
			let myChart = echarts.init(document.getElementById(str)),
				title = str == 'chart3' ? '本月' : '上月',
				data = [];

			dates.forEach((e, i) => {
				data.push([e, complete[i]])
			})

			let option = {
		        title: {
		            text: title + '完成情况',
		            subtext: dates[0] + ' ~ ' + dates[dates.length-1],
		        },
		        tooltip: {
		            trigger: 'axis'
		        },
		        xAxis: {
		            data: data.map(function (item) {
		                return item[0];
		            })
		        },
		        yAxis: {
		            splitLine: {
		                show: false
		            }
		        },
		        dataZoom: [{
		            startValue: '2014-06-01'
		        }, {
		            type: 'inside'
		        }],
		        series: {
		            name: '完成度',
		            type: 'line',
		            data: data.map(function (item) {
		                return item[1];
		            }),
		            markLine: {
		                silent: true,
		                data: [
		                	{ yAxis: 50 }, 
		                	{ yAxis: 100 }
		                ]
		            }
		        }
		    }
			myChart.setOption(option);
		},
		//周图表
		chart_week(str, params, datas){
			var myChart = echarts.init(document.getElementById(str)),
				cycle = '';

			switch(str){
				case 'chart1': cycle = '本周'; break;
				case 'chart2': cycle = '上周'; break;
				default: break;
			}

			var option = {
					title: {
						text: cycle + '完成情况',
        				subtext: params[0] + '~' + params[params.length-1],
					},
				    color: ['#009688'],
				    tooltip : {
				        trigger: 'axis',
				        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
				            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
				        }
				    },
				    grid: {
				        left: '3%', right: '4%', bottom: '3%', containLabel: true
				    },
				    xAxis : [
				        {
				            type : 'category',
				            data : ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				            axisTick: {
				                alignWithLabel: true
				            }
				        }
				    ],
				    yAxis : [
				        {
				            type : 'value'
				        }
				    ],
				    series : [
				        {
				            name:'完成度',
				            type:'bar',
				            barWidth: '60%',
				            data: datas
				        }
				    ]
				};

			myChart.setOption(option);
		},
		//本周、上周chart
		getWeekChart(){
			let me = this,
				params = this.globals.getWeekDate();

			setTimeout(function(){
				axios.post($base + 'task/getCycleTaskList', {
					mobile: me.select_name[me.nameVal].mobile,
					data: JSON.stringify(params),
					type: 'week'
				}).then(json => {
					let thisTask = [],
						lastTask = [],
						thisComplete = [],
						lastComplete = [];

					//重组本周数据
					params.thisWeek.forEach((e, ei) => {
						thisTask.push([]);
						json.data.forEach((d) => {
							//如果日期与截止时间相等
							if(e == moment(d.taskDate).format('YYYY-MM-DD')){
								thisTask[ei].push(d)
							}
						})
					})
					thisTask.forEach((e) => {
						let len = e.length,
							cop = 0;
						e.forEach((d) => {
							let taskDate = new Date(d.taskDate).getTime()+86400000;
							if(d.completeDate && new Date(d.completeDate).getTime() <= taskDate){
								cop++;
							}
						})
						if(len){
							thisComplete.push(cop / len * 100);
						}else{
							thisComplete.push(100);
						}
					})
					//重组上周数据
					params.lastWeek.forEach((e, ei) => {
						lastTask.push([]);
						json.data.forEach((d) => {
							//如果日期与截止时间相等
							if(e == moment(d.taskDate).format('YYYY-MM-DD')){
								lastTask[ei].push(d)
							}
						})
					})
					lastTask.forEach((e) => {
						let len = e.length,
							cop = 0;
						e.forEach((d) => {
							let taskDate = new Date(d.taskDate).getTime()+86400000;
							if(d.completeDate && new Date(d.completeDate).getTime() <= taskDate){
								cop++;
							}
						})
						if(len){
							lastComplete.push(cop / len * 100);
						}else{
							lastComplete.push(100);
						}
					})

					me.chart_week('chart1', params.thisWeek, thisComplete);
					me.chart_week('chart2', params.lastWeek, lastComplete);
				}).catch(json => {
					console.log(json)
				});
			}, 10)
		},
		//本月、上月chart
		getMonthChart(){
			let me = this,
				params = this.globals.getMonthDate();

			setTimeout(function(){
				axios.post($base + 'task/getCycleTaskList', {
					mobile: me.select_name[me.nameVal].mobile,
					data: JSON.stringify(params),
					type: 'month'
				}).then(json => {
					let thisTask = [],
						lastTask = [],
						thisComplete = [],
						lastComplete = [];

					//重组本月数据
					params.thisMonth.forEach((e, ei) => {
						thisTask.push([]);
						json.data.forEach((d) => {
							//如果日期与截止时间相等
							if(e == moment(d.taskDate).format('YYYY-MM-DD')){
								thisTask[ei].push(d)
							}
						})
					})
					thisTask.forEach((e) => {
						let len = e.length,
							cop = 0;
						e.forEach((d) => {
							let taskDate = new Date(d.taskDate).getTime()+86400000;
							if(d.completeDate && new Date(d.completeDate).getTime() <= taskDate){
								cop++;
							}
						})
						if(len){
							thisComplete.push(cop / len * 100);
						}else{
							thisComplete.push(100);
						}
					})
					//重组上周数据
					params.lastMonth.forEach((e, ei) => {
						lastTask.push([]);
						json.data.forEach((d) => {
							//如果日期与截止时间相等
							if(e == moment(d.taskDate).format('YYYY-MM-DD')){
								lastTask[ei].push(d)
							}
						})
					})
					lastTask.forEach((e) => {
						let len = e.length,
							cop = 0;
						e.forEach((d) => {
							let taskDate = new Date(d.taskDate).getTime()+86400000;
							if(d.completeDate && new Date(d.completeDate).getTime() <= taskDate){
								cop++;
							}
						})
						if(len){
							lastComplete.push(cop / len * 100);
						}else{
							lastComplete.push(100);
						}
					});

					me.chart_month('chart3', params.thisMonth, thisComplete);
					me.chart_month('chart4', params.lastMonth, lastComplete);
				}).catch(json => {
					console.log(json)
				});
			}, 10)
		},
		//chart调用
		getCharts(){
			for(var i=1; i<=4; i++){
				document.getElementById('chart'+i).style.display = 'none';
			}

			setTimeout(() => {
				switch(this.cycleVal){
					case 0:
						document.getElementById('chart1').style.display = 'block';
						document.getElementById('chart2').style.display = 'block';
						this.getWeekChart();
						break;
					case 1:
						document.getElementById('chart3').style.display = 'block';
						document.getElementById('chart4').style.display = 'block';
						this.getMonthChart();
						break;
					default: break;
				}
			}, 100)
		}
	},
	mounted(){

		//select_name
		if(this.userInfo.teamId){
			this.$store.state.userList.forEach(e => {
				this.select_name.push({
					userName: e.userName,
					mobile: e.mobile
				})
			})
			this.select_name.forEach((e, i) => {
				if(e.userName == this.userInfo.userName){
					this.nameVal = i;
				}
			})
			this.getCharts(0);
console.log(this.select_name)
		}
	}
}
</script>